package com.sjtu.rental.controller;

import java.util.Calendar;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sjtu.rental.common.Constant;
import com.sjtu.rental.entity.UserInfo;
import com.sjtu.rental.exception.RegisterException;
import com.sjtu.rental.form.RegisterForm;
import com.sjtu.rental.services.UserService;

@Controller
@RequestMapping("/register")
public class RegisterController {

	@Autowired
	private Validator registerForm;

	@Autowired
	private UserService userService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setValidator(this.registerForm);
	}

	@RequestMapping(method = RequestMethod.GET)
	public String init(Model model) {
		RegisterForm form = new RegisterForm();
		model.addAttribute("form", form);
		return "register";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String finish(
			@Valid @ModelAttribute("form") RegisterForm registerForm,
			BindingResult br, HttpSession session) {
		UserInfo user = registerForm.getUser();
		user.setUiState(Constant.USER_STATE_UNCONFIRM);
		user.setUiCreateDate(Calendar.getInstance().getTime());
		try {
			userService.saveOrUpdate(user);
			session.setAttribute("user", user);
		} catch (RegisterException e) {
			br.rejectValue(e.getKey(), e.getMessage());
			return "register";
		}
		
		return "redirect:/";
	}

}
